package com.sgcc.pda.hw.binder;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.sgcc.pda.common.aidl.CommonCallback;
import com.sgcc.pda.common.aidl.CommonParams;
import com.sgcc.pda.common.aidl.CommonResults;
import com.sgcc.pda.hw.IScannerManager;
import com.sgcc.pda.hw.IScannerReceiveDataCallback;
import com.sgcc.pda.hw.ReturnResult;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 扫描Scanner基础服务接口-封装给插件APP通过Binder调用
 *
 * @author Ben
 * @date 2019/06/11
 */
public class ScannerBinderUtil {
    /**
     * 成功字段
     */
    private static final String SUCCESS = "success";

    private static final String TAG = "ScannerBinderUtil";
    // 接口类名
    static final String CLASS_NAME = "com.sgcc.pda.hw.binder.ScannerBinderUtil";

    private IScannerManager mService = null;
    private boolean isBind = false;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IScannerManager.Stub.asInterface(service);
            isBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
            mService = null;
        }
    };

    private ScannerBinderUtil() {
    }

    private static class Instance {
        private static final ScannerBinderUtil mInstance = new ScannerBinderUtil();
    }

    /**
     * 单例
     */
    public static ScannerBinderUtil getInstance() {
        return Instance.mInstance;
    }

    /**
     * 绑定掌机基础服务提供接口的AIDL服务
     *
     * @param context
     * @return 是否绑定
     */
    public boolean bind(Context context) {
        if (isBind) return true;
        Intent intent = new Intent("com.sgcc.pda.hw.AIDL_SCANNER_SERVICE");
        intent.setPackage("com.sgcc.pda.hw");
        try {
            isBind = context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        } catch (SecurityException e) {
            Log.e(TAG, "bind: " + e.getMessage());
            isBind = false;
        }
        return isBind;
    }

    /**
     * 取消绑定掌机基础服务提供接口的AIDL服务
     *
     * @param context
     * @return 是否绑定
     */
    public void unbind(Context context) {
        try {
            context.unbindService(mConnection);
        } catch (Exception e) {
            Log.e(TAG, "unbind: " + e.getMessage());
        }
    }

    /**
     * 根据方法名执行对应的方法
     *
     * @param params   参数
     * @param callback 回调
     * @return 结果
     */
    public CommonResults execute(CommonParams params, CommonCallback callback) {
        String methodName = params.getMethodName();
        try {
            // 通过反射调用方法，方法参数与返回值必须统一成（CommonParams，CommonCallback，CommonResults）
            Method method = getClass().getMethod(methodName, CommonParams.class, CommonCallback.class);
            return (CommonResults) method.invoke(this, params, callback);
        } catch (Exception e) {
            Log.e(TAG, "execute: " + e.getMessage());
            return new CommonResults("-2", e.getMessage());
        }
    }


    /**
     * 扫描条形码二维码
     *
     * @param callback 返回结果回调
     *                 ReturnResult  :int code  0 成功  其他失败
     *                 :List<String> datas（code==0）:
     *                 0:data      返回扫描到的结果
     *                 :List<String> datas(code==其他): size==0
     */
    public CommonResults decodeScan(CommonParams params, final CommonCallback callback) throws RemoteException {

        mService.decodeScan(new IScannerReceiveDataCallback.Stub() {
            @Override
            public void onScannerReceiverData(ReturnResult returnResult) throws RemoteException {
                CommonResults results = new CommonResults("1", SUCCESS);
                if (returnResult != null) {
                    List<String> list = returnResult.getDatas();
                    if (list != null && !list.isEmpty()) {
                        String data = list.get(0);
                        results.addResult("scanResult", data);
                    }
                }
                callback.callback(results);
            }
        });
        return new CommonResults("1", SUCCESS);
    }

    /**
     * 扫描头通讯关闭和电源关闭
     *
     * @return 0：成功 其它：错误号
     */
    public CommonResults scannerDeInit(CommonParams params, CommonCallback callback) throws RemoteException {
//        String broadcastName = params.getString("broadcastName");
        ReturnResult returnResult = mService.Scanner_deInit();
        if (returnResult.getCode() == 0) {
            return new CommonResults("1", SUCCESS);
        } else {
            return new CommonResults("-" + returnResult.getCode(), "fail");
        }
    }

}
